package com.itcc.service.impl;

import com.itcc.dao.CartDao;
import com.itcc.dao.ProductDao;
import com.itcc.dao.impl.CartDaoImpl;
import com.itcc.dao.impl.ProductDaoImpl;
import com.itcc.entity.Cart;
import com.itcc.entity.Product;
import com.itcc.service.CartService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

public class CartServiceImpl implements CartService {


    @Override
    public void createCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException {

        //判断商品是否已经存在
        CartDao cartDao=new CartDaoImpl();

        Cart cart=cartDao.hasCart(uid,pid);

        if(cart!=null){
            cart.setCnum(cart.getCnum()+1);
            cartDao.updateCart(cart);
        }else{
            ProductDao productDao=new ProductDaoImpl();
            Product product=productDao.selectProductByPid(pid);
            cart=new Cart();
            cart.setCnum(1);
            cart.setPid(Integer.parseInt(pid));
            cart.setUid(uid);
            cart.setProduct(product);

            cartDao.insertCart(cart);
        }
    }

    @Override
    public List<Cart> findAll(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {

        CartDao cartDao=new CartDaoImpl();
        List<Cart> carts=cartDao.selectCartsByUid(uid);
        return carts;
    }

    @Override
    public void deleteCartByCid(String cid) throws SQLException {
        CartDao cartDao=new CartDaoImpl();
        cartDao.deleteCartByCid(cid);
    }

    @Override
    public void updateCartByCid(String cid,String price,String cnum) throws SQLException {
        BigDecimal pricebig=new BigDecimal(price);
        BigDecimal cnumbig=new BigDecimal(cnum);
        BigDecimal count=pricebig.multiply(cnumbig);

        CartDao cartDao=new CartDaoImpl();
        cartDao.updateByCid(count,cnumbig,cid);

    }

    @Override
    public void clearCart(String uid) throws SQLException {

        CartDao cartDao=new CartDaoImpl();
        cartDao.deleteCartByUid(uid);
    }
}
